/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Feedback;
import java.util.ArrayList;
import java.util.Collection;
import pojo.User;
import pojo.UserCoupon;
import pojo.Address;

/**
 *
 * @author A7med Kotb
 */
public class UserJpaController implements Serializable {

    public UserJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) throws RollbackFailureException, Exception {
        if (user.getFeedbackCollection() == null) {
            user.setFeedbackCollection(new ArrayList<Feedback>());
        }
        if (user.getUserCouponCollection() == null) {
            user.setUserCouponCollection(new ArrayList<UserCoupon>());
        }
        if (user.getAddressCollection() == null) {
            user.setAddressCollection(new ArrayList<Address>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Feedback> attachedFeedbackCollection = new ArrayList<Feedback>();
            for (Feedback feedbackCollectionFeedbackToAttach : user.getFeedbackCollection()) {
                feedbackCollectionFeedbackToAttach = em.getReference(feedbackCollectionFeedbackToAttach.getClass(), feedbackCollectionFeedbackToAttach.getFdbId());
                attachedFeedbackCollection.add(feedbackCollectionFeedbackToAttach);
            }
            user.setFeedbackCollection(attachedFeedbackCollection);
            Collection<UserCoupon> attachedUserCouponCollection = new ArrayList<UserCoupon>();
            for (UserCoupon userCouponCollectionUserCouponToAttach : user.getUserCouponCollection()) {
                userCouponCollectionUserCouponToAttach = em.getReference(userCouponCollectionUserCouponToAttach.getClass(), userCouponCollectionUserCouponToAttach.getUcId());
                attachedUserCouponCollection.add(userCouponCollectionUserCouponToAttach);
            }
            user.setUserCouponCollection(attachedUserCouponCollection);
            Collection<Address> attachedAddressCollection = new ArrayList<Address>();
            for (Address addressCollectionAddressToAttach : user.getAddressCollection()) {
                addressCollectionAddressToAttach = em.getReference(addressCollectionAddressToAttach.getClass(), addressCollectionAddressToAttach.getId());
                attachedAddressCollection.add(addressCollectionAddressToAttach);
            }
            user.setAddressCollection(attachedAddressCollection);
            em.persist(user);
            for (Feedback feedbackCollectionFeedback : user.getFeedbackCollection()) {
                User oldUserIdOfFeedbackCollectionFeedback = feedbackCollectionFeedback.getUserId();
                feedbackCollectionFeedback.setUserId(user);
                feedbackCollectionFeedback = em.merge(feedbackCollectionFeedback);
                if (oldUserIdOfFeedbackCollectionFeedback != null) {
                    oldUserIdOfFeedbackCollectionFeedback.getFeedbackCollection().remove(feedbackCollectionFeedback);
                    oldUserIdOfFeedbackCollectionFeedback = em.merge(oldUserIdOfFeedbackCollectionFeedback);
                }
            }
            for (UserCoupon userCouponCollectionUserCoupon : user.getUserCouponCollection()) {
                User oldUserIdOfUserCouponCollectionUserCoupon = userCouponCollectionUserCoupon.getUserId();
                userCouponCollectionUserCoupon.setUserId(user);
                userCouponCollectionUserCoupon = em.merge(userCouponCollectionUserCoupon);
                if (oldUserIdOfUserCouponCollectionUserCoupon != null) {
                    oldUserIdOfUserCouponCollectionUserCoupon.getUserCouponCollection().remove(userCouponCollectionUserCoupon);
                    oldUserIdOfUserCouponCollectionUserCoupon = em.merge(oldUserIdOfUserCouponCollectionUserCoupon);
                }
            }
            for (Address addressCollectionAddress : user.getAddressCollection()) {
                User oldUserIdOfAddressCollectionAddress = addressCollectionAddress.getUserId();
                addressCollectionAddress.setUserId(user);
                addressCollectionAddress = em.merge(addressCollectionAddress);
                if (oldUserIdOfAddressCollectionAddress != null) {
                    oldUserIdOfAddressCollectionAddress.getAddressCollection().remove(addressCollectionAddress);
                    oldUserIdOfAddressCollectionAddress = em.merge(oldUserIdOfAddressCollectionAddress);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User persistentUser = em.find(User.class, user.getId());
            Collection<Feedback> feedbackCollectionOld = persistentUser.getFeedbackCollection();
            Collection<Feedback> feedbackCollectionNew = user.getFeedbackCollection();
            Collection<UserCoupon> userCouponCollectionOld = persistentUser.getUserCouponCollection();
            Collection<UserCoupon> userCouponCollectionNew = user.getUserCouponCollection();
            Collection<Address> addressCollectionOld = persistentUser.getAddressCollection();
            Collection<Address> addressCollectionNew = user.getAddressCollection();
            List<String> illegalOrphanMessages = null;
            for (Address addressCollectionOldAddress : addressCollectionOld) {
                if (!addressCollectionNew.contains(addressCollectionOldAddress)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Address " + addressCollectionOldAddress + " since its userId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Feedback> attachedFeedbackCollectionNew = new ArrayList<Feedback>();
            for (Feedback feedbackCollectionNewFeedbackToAttach : feedbackCollectionNew) {
                feedbackCollectionNewFeedbackToAttach = em.getReference(feedbackCollectionNewFeedbackToAttach.getClass(), feedbackCollectionNewFeedbackToAttach.getFdbId());
                attachedFeedbackCollectionNew.add(feedbackCollectionNewFeedbackToAttach);
            }
            feedbackCollectionNew = attachedFeedbackCollectionNew;
            user.setFeedbackCollection(feedbackCollectionNew);
            Collection<UserCoupon> attachedUserCouponCollectionNew = new ArrayList<UserCoupon>();
            for (UserCoupon userCouponCollectionNewUserCouponToAttach : userCouponCollectionNew) {
                userCouponCollectionNewUserCouponToAttach = em.getReference(userCouponCollectionNewUserCouponToAttach.getClass(), userCouponCollectionNewUserCouponToAttach.getUcId());
                attachedUserCouponCollectionNew.add(userCouponCollectionNewUserCouponToAttach);
            }
            userCouponCollectionNew = attachedUserCouponCollectionNew;
            user.setUserCouponCollection(userCouponCollectionNew);
            Collection<Address> attachedAddressCollectionNew = new ArrayList<Address>();
            for (Address addressCollectionNewAddressToAttach : addressCollectionNew) {
                addressCollectionNewAddressToAttach = em.getReference(addressCollectionNewAddressToAttach.getClass(), addressCollectionNewAddressToAttach.getId());
                attachedAddressCollectionNew.add(addressCollectionNewAddressToAttach);
            }
            addressCollectionNew = attachedAddressCollectionNew;
            user.setAddressCollection(addressCollectionNew);
            user = em.merge(user);
            for (Feedback feedbackCollectionOldFeedback : feedbackCollectionOld) {
                if (!feedbackCollectionNew.contains(feedbackCollectionOldFeedback)) {
                    feedbackCollectionOldFeedback.setUserId(null);
                    feedbackCollectionOldFeedback = em.merge(feedbackCollectionOldFeedback);
                }
            }
            for (Feedback feedbackCollectionNewFeedback : feedbackCollectionNew) {
                if (!feedbackCollectionOld.contains(feedbackCollectionNewFeedback)) {
                    User oldUserIdOfFeedbackCollectionNewFeedback = feedbackCollectionNewFeedback.getUserId();
                    feedbackCollectionNewFeedback.setUserId(user);
                    feedbackCollectionNewFeedback = em.merge(feedbackCollectionNewFeedback);
                    if (oldUserIdOfFeedbackCollectionNewFeedback != null && !oldUserIdOfFeedbackCollectionNewFeedback.equals(user)) {
                        oldUserIdOfFeedbackCollectionNewFeedback.getFeedbackCollection().remove(feedbackCollectionNewFeedback);
                        oldUserIdOfFeedbackCollectionNewFeedback = em.merge(oldUserIdOfFeedbackCollectionNewFeedback);
                    }
                }
            }
            for (UserCoupon userCouponCollectionOldUserCoupon : userCouponCollectionOld) {
                if (!userCouponCollectionNew.contains(userCouponCollectionOldUserCoupon)) {
                    userCouponCollectionOldUserCoupon.setUserId(null);
                    userCouponCollectionOldUserCoupon = em.merge(userCouponCollectionOldUserCoupon);
                }
            }
            for (UserCoupon userCouponCollectionNewUserCoupon : userCouponCollectionNew) {
                if (!userCouponCollectionOld.contains(userCouponCollectionNewUserCoupon)) {
                    User oldUserIdOfUserCouponCollectionNewUserCoupon = userCouponCollectionNewUserCoupon.getUserId();
                    userCouponCollectionNewUserCoupon.setUserId(user);
                    userCouponCollectionNewUserCoupon = em.merge(userCouponCollectionNewUserCoupon);
                    if (oldUserIdOfUserCouponCollectionNewUserCoupon != null && !oldUserIdOfUserCouponCollectionNewUserCoupon.equals(user)) {
                        oldUserIdOfUserCouponCollectionNewUserCoupon.getUserCouponCollection().remove(userCouponCollectionNewUserCoupon);
                        oldUserIdOfUserCouponCollectionNewUserCoupon = em.merge(oldUserIdOfUserCouponCollectionNewUserCoupon);
                    }
                }
            }
            for (Address addressCollectionNewAddress : addressCollectionNew) {
                if (!addressCollectionOld.contains(addressCollectionNewAddress)) {
                    User oldUserIdOfAddressCollectionNewAddress = addressCollectionNewAddress.getUserId();
                    addressCollectionNewAddress.setUserId(user);
                    addressCollectionNewAddress = em.merge(addressCollectionNewAddress);
                    if (oldUserIdOfAddressCollectionNewAddress != null && !oldUserIdOfAddressCollectionNewAddress.equals(user)) {
                        oldUserIdOfAddressCollectionNewAddress.getAddressCollection().remove(addressCollectionNewAddress);
                        oldUserIdOfAddressCollectionNewAddress = em.merge(oldUserIdOfAddressCollectionNewAddress);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Address> addressCollectionOrphanCheck = user.getAddressCollection();
            for (Address addressCollectionOrphanCheckAddress : addressCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Address " + addressCollectionOrphanCheckAddress + " in its addressCollection field has a non-nullable userId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Feedback> feedbackCollection = user.getFeedbackCollection();
            for (Feedback feedbackCollectionFeedback : feedbackCollection) {
                feedbackCollectionFeedback.setUserId(null);
                feedbackCollectionFeedback = em.merge(feedbackCollectionFeedback);
            }
            Collection<UserCoupon> userCouponCollection = user.getUserCouponCollection();
            for (UserCoupon userCouponCollectionUserCoupon : userCouponCollection) {
                userCouponCollectionUserCoupon.setUserId(null);
                userCouponCollectionUserCoupon = em.merge(userCouponCollectionUserCoupon);
            }
            em.remove(user);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
